<template>
  <div>
    <div id="search">
      <el-form :inline="true" :model="StudentSearch" class="demo-form-inline">
        <el-form-item label="姓名">
          <el-input v-model="StudentSearch.name" placeholder="请输入学生姓名"></el-input>
        </el-form-item>
        <el-form-item label="学号">
          <el-input v-model="StudentSearch.studentNo" placeholder="请输入学生学号"></el-input>
        </el-form-item>
        <el-form-item label="课程">
          <el-select clearable v-model="StudentSearch.courseId" placeholder="请选择课程">
            <el-option
                v-for="item in CourseList"
                :key="item.id"
                :label="item.courseName"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="onSearchSubmit" size="small">搜索</el-button>
          <el-button type="primary" icon="el-icon-upload2" size="small" @click="exportStudentExcel" >导出</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div id="header-bth">
      <el-button icon="el-icon-plus" type="primary" plain size="mini"@click="showAddScore" >新增</el-button>
      <el-button icon="el-icon-delete" type="danger" plain size="mini"
                 :disabled="this.multipleSelection.length>0?false:true"  @click="deleteAll">删除
      </el-button>
      <el-button icon="el-icon-download" type="info"  size="mini" @click="uploadDialogVisible=true">导入</el-button>
    </div>
    <div id="role-table">
      <el-table
          :header-cell-style="{background:'rgb(242, 242, 242)'}"
          style="width: 100%;
          text-align: center"
          :data="tableData"
          :row-style="{height: '50px'}"
          :cell-style="{padding: '0'}"
          @selection-change="handleSelectionChange"
          >
        <el-table-column
            type="selection"
            width="55"
            align="center"
        >
        </el-table-column>
        <el-table-column label="姓名">
          <template slot-scope="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="年龄">
          <template slot-scope="scope">
            <span>{{ scope.row.age }}</span>
          </template>
        </el-table-column>
        <el-table-column label="班级">
          <template slot-scope="scope">
            <span>{{ scope.row.clazz }}</span>
          </template>
        </el-table-column>
        <el-table-column label="课程">
          <template slot-scope="scope">
            <span>{{ scope.row.courseName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="入学时间" >
          <template slot-scope="scope">
            <span>{{ scope.row.schoolYear}}</span>
          </template>
        </el-table-column>
        <el-table-column label="学号" >
          <template slot-scope="scope">
            <span>{{ scope.row.studentNo}}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
                icon="el-icon-edit"
                size="mini"
                @click="handleEdit(scope.$index, scope.row)">
            </el-button>
            <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="handleDelete(scope.row.id)">
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div id="nav-page">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="pageSizes"
          :current-page="StudentSearch.page"
          :page-size="StudentSearch.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
    <!--添加 编辑角色信息弹窗-->
    <el-dialog :title="dialogTitle" :visible.sync="addScoreFormVisible" width="50%" @close="clearInfo">
      <el-form :model="StudentForm" ref="studentInfo" :rules="studentRules" label-width="90px" size="medium">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="StudentForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="StudentForm.age" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="班级" prop="clazz">
          <el-input v-model="StudentForm.clazz" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="课程" prop="courseId">
          <el-select v-model="StudentForm.courseId" placeholder="请选择课程">
            <el-option
                v-for="item in CourseList"
                :key="item.id"
                :label="item.courseName"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="入学日期" prop="schoolYear">
          <el-date-picker type="date" value-format="yyyy-MM-dd" placeholder="选择日期" v-model="StudentForm.schoolYear" style="width: 100%;"></el-date-picker>
        </el-form-item>
        <el-form-item label="学号" prop="studentNo">
          <el-input v-model="StudentForm.studentNo" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit('studentInfo')">确 定</el-button>
      </div>
    </el-dialog>

    <!--批量导入文件弹窗    -->
    <el-dialog title="文件上传" :visible.sync="uploadDialogVisible" width="27%" @close="clearInfo">
      <el-upload
          ref='upload'
          drag
          class="upload-demo"
          :headers="config"
          action='#'
          name='file'
          accept=".xls,.xlsx"
          :limit="1"
          :show-file-list="false"
          :http-request="uploadFile"

      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
    </el-dialog>

  </div>
</template>

<script>
import instance from "@/request/request";
import {batchStudentApi, exportStudentExcelApi} from "@/request/api";
import fileDownload from "js-file-download";
export default {
  name: "StudentView",
  data() {
    return {
      tableData: [],
      pageSizes: [3, 5, 10, 15],
      total: 0,
      addScoreFormVisible: false,
      dialogTitle: '',
      StudentForm: {},
      StudentSearch: {  // 搜索数据
        page: 1,
        limit: 5
      },
      studentRules: {
        name: [{required: true, message: '请输入学生姓名', trigger: 'blur'}],
        age: [{required: true, message: '请输入学生年龄', trigger: 'blur'}],
        clazz: [{required: true, message: '请输入学生班级', trigger: 'blur'}],
        courseId: [{required: true, message: '请选择课程', trigger: 'change' }],
        schoolYear:[{ required: true, message: '请选择日期', trigger: 'change' }],
        studentNo:[{required: true, message: '请输入学生学号', trigger: 'blur'}]
      },
      //课程课表
      CourseList:[],
      multipleSelection:[],
      //批量导入
      uploadDialogVisible:false,
      config:{
        "token":sessionStorage.getItem("token")
      }
    }
  },
  created() {
    this.getStudentSearch()
    this.getscoreList()
  },
  methods: {
    //导入文件
    uploadFile(file){
      // 创建表单数据对象 封装file数据
      let formData = new FormData();
      // username = tom    file.file 获取上传文件数据
      formData.append("file",file.file)
      batchStudentApi(formData).then(response=>{
        if (response.code==200){
          this.$message.success(response.msg)
          this.uploadDialogVisible= false
          this.getStudentSearch()
          this.$refs.upload.clearFiles(); //上传成功之后清除历史记录
          return
        }
        this.$message.warning(response.msg)
        this.$refs.upload.clearFiles(); //上传成功之后清除历史记录
      }).catch(error=>{
        this.$message.error("连接失败")
      })
    },
    exportStudentExcel(){
      exportStudentExcelApi(this.StudentSearch).then(response=>{
        fileDownload(response, new Date().getTime()+".xlsx"); // 使用js-file-download来接收二进制流然后下载
      })
    },

    //获取课程表信息
    getscoreList(){
      instance.get("/course/list").then(res=>{
        if(res.code==200){
          this.CourseList=res.data
        }
      }).catch(erro=>{
        this.$message.error("请求失败！")
      })
    },
    //获取角色信息
    getStudentSearch() {
      instance.get("/student/list",{params:this.StudentSearch}).then(res=>{
        if(res.code==200){
          this.tableData=res.data.student
          this.total=res.data.total
          return
        }
        this.$message.error(res.msg)
      }).catch(erro=>{
        this.$message.error("请求失败！")
      })
    },
    // 编辑角色
    handleEdit(index, row) {
      this.dialogTitle = "编辑学生"
      this.addScoreFormVisible= true
      var dept=Object.assign({},row)
      this.StudentForm=dept
    },
    //更新和添加用户信息
    submit(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          instance.post("/student/addorupdate",this.StudentForm).then(res=>{
            if (res.code==200){
              this.$message.success(res.msg)
              this.addScoreFormVisible=false
              this.getStudentSearch()
              return
            }
            this.$message.warning(res.msg)
          }).catch(erro=>{
            this.$message.error("请求失败")
          })

        } else {
          console.log('error submit!!');
          return false;
        }
      })
    },
    // 删除角色
    handleDelete(id) {
      this.$confirm('确认要删除？', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.multipleSelection=[id]
        instance.delete("/student/delete",{data:this.multipleSelection}).then(res=>{
          if(res.code==200){
            this.$message.success(res.msg)
            this.getStudentSearch()
            this.multipleSelection=[]
            return
          }
          this.$message.warning(res.msg)
        }).catch(erro=>{
          this.$message.error("请求失败！")
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消！'
        })
      })
    },
    deleteAll() {
      this.$confirm('确认要删除？', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        instance.delete("/student/delete",{data:this.multipleSelection}).then(res=>{
          if(res.code==200){
            this.$message.success(res.msg)
            this.getStudentSearch()
            return
          }
          this.$message.warning(res.msg)
        }).catch(erro=>{
          this.$message.error("请求失败！")
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消！'
        })
      })
    },
    // 搜索角色
    onSearchSubmit() {
      this.StudentSearch.page = 1
      this.StudentSearch.limit = 5
      this.getStudentSearch()
    },
    // 改变每页显示的条数触发
    handleSizeChange(val) {
      this.StudentSearch.limit = val;
      this.getStudentSearch()
    },
    // 改变页码触发
    handleCurrentChange(val) {
      this.StudentSearch.page = val;
      this.getStudentSearch()
    },
    // 显示弹出等
    showAddScore() {
      this.dialogTitle = "添加学生"
      this.addScoreFormVisible = true
      this.StudentForm = {}
    },
    //清空校验规则
    clearInfo() {
      this.$refs.studentInfo.clearValidate()
      this.$refs.upload.clearFiles()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map(s=>s.id);
    },
  },
}
</script>

<style >
#search {
  width: 100%;
  height: 50px;
  border-bottom: 1px solid #eee;
}

#search, #header-bth, #nav-page {
  margin: 15px;
}

#role-table {
  width: 100%;
}
</style>
